import DexieCtx from '@/utils/dexiectx';
import GramClient from "@/utils/gramclient";

class GramTgweb {
  /**
   * 
   * @param {*} table 游戏表名/project.name/gameKey
   * @param {*} platform ios|android，默认ios
   */
  constructor(table, platform) {
    this.table = table
    this.platform = platform ?? "ios"
  }

  async allRun() {
    this.dexie = await DexieCtx.db()
    const allAccounts = await this.dexie.accounts.where("session").notEqual("").toArray()
    const project = await this.dexie.projects.get({
      name: this.table,
    })
    let inviteList = project.inviteList || []

    let sepIndex = 0;
    const groupStep = 10
    while (true) {
      if (sepIndex >= allAccounts.length) {
        break;
      }
      const start = sepIndex
      const end = Math.min(sepIndex + groupStep, allAccounts.length)

      try {
        let promiseList = []
        for (let index = start; index < end; index++) {
          const account = allAccounts[index];
          const gameInfo = await this.dexie[this.table].get({
            phone: account.phone,
          })
          const extGameInfo = gameInfo ?? {}
          if (inviteList.length > 0) {
            const inviteUrl = inviteList[index % inviteList.length]
            extGameInfo.inviteUrl = inviteUrl
          }
          extGameInfo.bot = project.bot
          extGameInfo.channel = project.channel
          extGameInfo.gameUrl = project.gameUrl
          extGameInfo.phone = account.phone
          const prms = this.run(account, extGameInfo)
          promiseList.push(prms)
        }
        await Promise.allSettled(promiseList)
        console.log(Date() + "Cows tgweb finished " + start + "~" + end)
      } catch (error) {
        console.error(error)
      } finally {
        sepIndex = end
      }
    }
  }

  async run(account, extGameInfo) {
    const client = new GramClient(account)
    try {
      await client.open()
      // /start -> bot
      if (extGameInfo.isJoinBot != true) {
        let startParam = null
        if (this.isBotUrl(extGameInfo.inviteUrl)) {
          startParam = this.getStartParamOfUrl(extGameInfo.inviteUrl)
        }
        const isJoined = await client.startBot(extGameInfo.bot, startParam)
        extGameInfo.isJoinBot = isJoined
        console.log(this.table, account.phone, "startBot")
      }
      // 加入频道
      // if (extGameInfo.isJoinChannel != true) {
      //   const isJoined = await client.joinChannel(extGameInfo.channel)
      //   extGameInfo.isJoinChannel = isJoined
      //   console.log(this.table, account.phone, "joinChannel")
      // }
      let gameUrl = this.isGameUrl(extGameInfo.inviteUrl) ? extGameInfo.inviteUrl : extGameInfo.gameUrl;
      if (gameUrl == null || gameUrl == '') {
        gameUrl = "https://t.me/cowscoin_bot/app?startapp=i1a4266844";  
      }
      
      const bot = extGameInfo.bot;
      let startParam = null
      if (this.isGameUrl(gameUrl)) {
        startParam = this.getStartParamOfUrl(gameUrl)
      }
      const url = await client.getTgwebUrl(bot, gameUrl, this.platform, startParam);

      console.log("getTgwebUrl", bot, gameUrl, startParam)
      console.log(this.table, account.phone, url);
      extGameInfo.tgweb = url
      await this.updateResultTable(client.account, extGameInfo)
    } catch (error) {
      console.error(account.phone, error)
    } finally {
      await client.close()
    }
  }

  async updateResultTable(account, extGameInfo) {
    if (extGameInfo.tgweb == null) {
      return
    }
    const oldValue = await this.dexie[this.table].get({
      phone: extGameInfo.phone
    })
    const dateStr = (new Date()).toLocaleString()
    extGameInfo.tokenupdate = dateStr
    if (oldValue == null) {
      await this.dexie[this.table].add(extGameInfo)
    } else {
      await this.dexie[this.table].where("phone").equals(extGameInfo.phone).modify(extGameInfo)
    }
  }

  isBotUrl(url) {
    if (url == null) {
      return false
    }
    return url.indexOf("start=") >= 0
  }

  isGameUrl(url) {
    if (url == null) {
      return false
    }
    return url.indexOf("startapp=") >= 0
  }

  getStartParamOfUrl(url) {
    if (url.indexOf("start=") >= 0) {
      return url.split("start=")[1]
    } else if (url.indexOf("startapp=") >= 0) {
      return url.split("startapp=")[1]
    } else {
      return null
    }
  }
}

export default GramTgweb